'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.connectModel = exports.genCheckUpdate = undefined;

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _shallowEqual = require('./shallowEqual');

var _uniqueId = require('lodash/uniqueId');

var _uniqueId2 = _interopRequireDefault(_uniqueId);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var genCheckUpdate = exports.genCheckUpdate = function genCheckUpdate(_ref) {
    var check = _ref.check,
        update = _ref.update,
        log = _ref.log;

    var _oldData = void 0;
    var checkCount = 0;
    var changeCount = 0;
    return function () {
        var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
            _ref2$checkArgs = _ref2.checkArgs,
            checkArgs = _ref2$checkArgs === undefined ? [] : _ref2$checkArgs,
            _ref2$updateArgs = _ref2.updateArgs,
            updateArgs = _ref2$updateArgs === undefined ? [] : _ref2$updateArgs;

        var oldData = _oldData;
        var newData = check.call.apply(check, [this, {
            oldData: oldData
        }].concat((0, _toConsumableArray3.default)(checkArgs)));
        var isChange = !(0, _shallowEqual.shallowEqual)(oldData, newData);
        log && log('checkChangeUpdate shallowEqual:', checkCount++, oldData, newData);
        if (isChange) {
            log && log('checkChangeUpdate isChange:', changeCount++);
            _oldData = newData;
            update.call.apply(update, [this, newData, oldData].concat((0, _toConsumableArray3.default)(updateArgs)));
        }
    };
};

var connectModel = exports.connectModel = function connectModel() {
    var _this = this;

    var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref3$namespace = _ref3.namespace,
        namespace = _ref3$namespace === undefined ? (0, _uniqueId2.default)('attachModel_') : _ref3$namespace,
        model = _ref3.model,
        log = _ref3.log,
        _ref3$check = _ref3.check,
        check = _ref3$check === undefined ? function () {
        return model.getData();
    } : _ref3$check,
        _ref3$update = _ref3.update,
        update = _ref3$update === undefined ? function () {
        log && log('请调用更新方法');
    } : _ref3$update;

    var checkUpdate = genCheckUpdate({
        check: check,
        update: update,
        log: log
    });
    var fn = function fn() {
        checkUpdate.call(_this);
    };
    model.onChange(namespace, fn);
    var cancel = function cancel() {
        model.offChange(namespace, fn);
    };
    return {
        cancel: cancel
    };
};
exports.default = connectModel;